<template>
  <div
    class="agent-card"
    :class="{
      grouped: isGrouped,
      'agent-card-animation': !isGrouped,
    }"
    :style="cardStyle"
    :data-agent-type="agent.type"
    :data-agent-name="agent.name"
  >
    <!-- Agent头部 - 仅在非分组模式下显示 -->
    <div v-if="!isGrouped" class="flex items-center mb-1.5 relative">
      <div
        class="w-7 h-7 rounded-md flex items-center justify-center mr-2.5 relative overflow-hidden"
        :style="iconContainerStyle"
      >
        <div v-html="agentIcon"></div>
        <div
          class="absolute top-0 right-0 bottom-0 left-0 opacity-10"
          :style="iconOverlayStyle"
        ></div>
      </div>
      <div class="flex items-center">
        <div
          v-if="agent.number !== undefined"
          class="flex items-center justify-center rounded-full mr-1.5 w-5 h-5"
          :style="numberStyle"
        >
          {{ agent.number }}
        </div>
        <div class="text-sm font-medium" :style="{ color: iconColor }">
          {{ agent.name }}
        </div>
      </div>
    </div>

    <!-- 加载指示器 -->
    <div v-if="loading" class="flex items-center my-2.5 text-gray-500">
      <div
        class="w-4 h-4 border-2 border-gray-200 border-t-indigo-500 rounded-full mr-2 animate-spin"
      ></div>
      <span class="text-xs">正在加载...</span>
    </div>

    <!-- Agent内容 -->
    <div
      v-if="!loading"
      :class="{ 'mt-1.5': !isGrouped }"
      class="animate-fadeIn relative overflow-hidden"
    >
      <!-- 角标 -->
      <div
        v-if="agent.tag"
        class="absolute z-10 top-4 right-[-24px] text-xs px-6 py-0.5 text-white transform rotate-45"
        :style="{ backgroundColor: agentColor }"
      >
        {{ agent.tag }}
      </div>
      <!-- 文本类型 -->
      <div
        v-if="agent.type === 'text'"
        class="text-gray-600 text-xs leading-relaxed px-0.5"
      >
        <p>{{ displayText }}</p>
      </div>

      <!-- 结果类型 -->
      <div
        v-else-if="agent.type === 'result'"
        class="bg-white rounded-md p-3 border border-gray-100"
      >
        <div class="flex items-center mb-2">
          <div
            class="w-2 h-2 rounded-full mr-2"
            :style="{ backgroundColor: agentColor }"
          ></div>
          <div class="text-sm font-medium text-gray-700">
            {{ agent.title || "收集结果" }}
          </div>
        </div>
        <div
          v-if="agent.actionText"
          class="flex items-center mb-2 text-xs text-gray-500"
        >
          <span>{{ agent.actionText }}</span>
        </div>
        <!-- <div v-if="agent.actionText" class="text-center mt-3">
          <a
            href="javascript:;"
            class="text-xs text-blue-500 hover:text-blue-600"
            @click="$emit('action-click', agent)"
          >
            {{ agent.actionText }}
          </a>
        </div> -->
      </div>

      <!-- 进度类型 -->
      <div
        v-else-if="agent.type === 'progress'"
        class="bg-white rounded-md p-3"
      >
        <div class="mb-2 flex items-center">
          <div
            class="w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center mr-2"
          >
            <span class="text-xs text-blue-500 font-medium">{{
              agent.number
            }}</span>
          </div>
          <div class="text-sm font-medium text-gray-700">
            {{ agent.title || "进度" }}
          </div>
        </div>
        <div class="pl-8 border-l-2 border-blue-200 ml-3 py-1">
          <div
            v-for="(step, index) in agent.steps || []"
            :key="index"
            class="relative pb-2 last:pb-0 flex items-center"
          >
            <div
              class="absolute left-[-13px] top-1 w-2 h-2 rounded-full bg-blue-400"
              :class="{
                'bg-blue-200': step.pending,
                'bg-blue-500': step.active,
              }"
            ></div>
            <div class="text-xs text-gray-600">
              {{ step.text }}
            </div>
          </div>
        </div>
      </div>

      <!-- 检索类型 -->
      <div
        v-else-if="agent.type === 'search'"
        class="bg-white rounded-md p-3 border border-gray-100"
      >
        <div v-if="agent.isInitializing" class="text-gray-500 text-xs my-1">
          正在初始化...
        </div>

        <div v-if="agent.messages && agent.messages.length > 0" class="mt-1">
          <div v-for="(message, index) in agent.messages" :key="index">
            <div v-if="message.type === 'mcp'" class="flex items-center my-1">
              <a
                href="javascript:;"
                class="flex items-center text-[#6366F1] text-xs py-1 px-4 rounded-md border border-blue-100 bg-blue-50 hover:bg-blue-100"
              >
                <span class="mr-2">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  >
                    <path
                      d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"
                    ></path>
                    <path
                      d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"
                    ></path>
                  </svg>
                </span>
                <span>MCP连接</span>
                <span v-if="message.text" class="ml-2 text-gray-500">{{
                  message.text
                }}</span>
              </a>
            </div>
            <div
              v-if="message.type === 'text'"
              class="text-xs py-1 text-gray-500"
            >
              {{ message.text }}
            </div>
          </div>
        </div>
      </div>

      <!-- 汇总结果类型 -->
      <div
        v-else-if="agent.type === 'summary'"
        class="bg-white rounded-md p-3 border border-gray-100 relative"
      >
        <!-- <div class="flex items-center">
          <div
            class="w-8 h-8 rounded-md bg-indigo-100 flex items-center justify-center mr-3"
          >
            <div v-html="summaryIcon"></div>
          </div>
          <div class="text-sm font-medium text-gray-700">
            {{ agent.title || "汇总结果" }}
          </div>
        </div> -->
        <div class="mt-1 text-sm">
          <span class="mr-1">已为您找到</span>
          <span class="text-indigo-500 font-bold text-lg">{{
            agent.count || 0
          }}</span>
          <span class="ml-1">家相关企业信息</span>
        </div>
        <div v-if="agent.actionText" class="text-xs text-gray-500 mt-2">
          <a
            href="javascript:;"
            class="hover:text-gray-700"
            @click="handleClickAction"
          >
            {{ agent.actionText }}
          </a>
        </div>
      </div>
    </div>
    <AgentResultModal
      v-if="agentResultModalVisible"
      @close="handleCloseAgentResultModal"
    />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import AgentResultModal from "./agent-result-modal.vue";

const props = defineProps({
  agent: {
    type: Object,
    required: true,
  },
  execStep: {
    type: Number,
    default: 0,
  },
  isGrouped: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["action-click"]);

const loading = ref(false);
const agentResultModalVisible = ref(false);

// 智能体颜色映射，根据智能体类型或名称分配不同颜色
const AGENT_COLOR_MAP = {
  数据收集助手: {
    primary: "#6366f1", // 蓝紫色
    secondary: "#e0e7ff", // 对应的浅色背景
    icon: "cpu", // 文档图标
  },
  数据分析智能体: {
    primary: "#0ea5e9", // 天蓝色
    secondary: "#e0f2fe", // 对应的浅色背景
    icon: "briefcase", // 业务图标
  },
  数据汇总结果: {
    primary: "#6366f1", // 蓝紫色
    secondary: "#e0e7ff", // 对应的浅色背景
    icon: "file-text", // 文档图标
  },
  智能体3: {
    primary: "#10b981", // 绿色
    secondary: "#d1fae5", // 对应的浅色背景
    icon: "cpu",
  },
  智能体4: {
    primary: "#f59e0b", // 琥珀色
    secondary: "#fef3c7", // 对应的浅色背景
    icon: "zap",
  },
  // 默认颜色，用于未定义的智能体
  default: {
    primary: "#6366f1", // 默认蓝紫色
    secondary: "#e0e7ff", // 对应的浅色背景
    icon: "activity",
  },
};

// 文本类型卡片颜色
const TEXT_DOT_COLOR = "#6366f1"; // 主色调-蓝紫色
const TEXT_BG_COLOR = "#e0e7ff";

// 获取智能体的颜色配置
const getAgentColorConfig = (agentName) => {
  return AGENT_COLOR_MAP[agentName] || AGENT_COLOR_MAP["default"];
};

// 获取智能体图标
const getAgentIcon = (agentName) => {
  const config = getAgentColorConfig(agentName);
  const iconType = config.icon;

  // 根据图标类型返回相应的SVG
  switch (iconType) {
    case "scale":
      return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3v3a2 2 0 0 1-2 2H3"></path><path d="M21 8h-3a2 2 0 0 1-2-2V3"></path><path d="M3 16h3a2 2 0 0 1 2 2v3"></path><path d="M16 21v-3a2 2 0 0 1 2-2h3"></path></svg>`;
    case "briefcase":
      return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="20" height="14" rx="2" ry="2"></rect><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"></path></svg>`;
    case "cpu":
      return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="2" ry="2"></rect><rect x="9" y="9" width="6" height="6"></rect><line x1="9" y1="1" x2="9" y2="4"></line><line x1="15" y1="1" x2="15" y2="4"></line><line x1="9" y1="20" x2="9" y2="23"></line><line x1="15" y1="20" x2="15" y2="23"></line><line x1="20" y1="9" x2="23" y2="9"></line><line x1="20" y1="14" x2="23" y2="14"></line><line x1="1" y1="9" x2="4" y2="9"></line><line x1="1" y1="14" x2="4" y2="14"></line></svg>`;
    case "file-text":
      return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>`;
    case "zap":
      return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon></svg>`;
    default:
      return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="10" rx="2"></rect><circle cx="12" cy="5" r="2"></circle><path d="M12 7v4"></path><line x1="8" y1="15" x2="8" y2="17"></line><line x1="16" y1="15" x2="16" y2="17"></line></svg>`;
  }
};

// 汇总图标
const summaryIcon = computed(() => {
  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#6366f1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"></line><line x1="8" y1="12" x2="21" y2="12"></line><line x1="8" y1="18" x2="21" y2="18"></line><line x1="3" y1="6" x2="3.01" y2="6"></line><line x1="3" y1="12" x2="3.01" y2="12"></line><line x1="3" y1="18" x2="3.01" y2="18"></line></svg>`;
});

// 将十六进制颜色转换为RGB格式
const hexToRgb = (hex) => {
  // 移除可能的 # 前缀
  hex = hex.replace("#", "");

  // 解析十六进制值
  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);

  return `${r}, ${g}, ${b}`;
};

// 计算显示文本
const displayText = computed(() => {
  let text = props.agent.text;
  try {
    const textObj = JSON.parse(props.agent.text);
    text = textObj.text;
  } catch (e) {
    /* empty */
  }
  return text;
});

// 获取智能体颜色配置
const colorConfig = computed(() => getAgentColorConfig(props.agent.name));
const agentColor = computed(() => colorConfig.value.primary);
const agentBgColor = computed(() => colorConfig.value.secondary);
const agentIcon = computed(() => getAgentIcon(props.agent.name));

// 根据类型设置不同颜色
const iconBg = computed(() =>
  props.agent.type === "text" ? TEXT_BG_COLOR : agentBgColor.value
);
const iconColor = computed(() =>
  props.agent.type === "text" ? TEXT_DOT_COLOR : agentColor.value
);

// 为不同智能体准备边框样式
const borderStyle = computed(() => {
  if (props.agent.type === "text") return "border-l-[3px] border-l-indigo-500";
  return "border-l-[3px]";
});

// 卡片样式
const cardStyle = computed(() => {
  if (props.isGrouped) return {};

  return {
    borderLeftColor: iconColor.value,
    background: `linear-gradient(135deg, ${agentBgColor.value} 0%, #ffffff 150%)`,
    boxShadow: `0 4px 12px rgba(${hexToRgb(
      iconColor.value
    )}, 0.12), 0 2px 4px rgba(${hexToRgb(iconColor.value)}, 0.05)`,
    borderRadius: "8px",
    transition: "all 0.3s ease",
    padding: "0.75rem",
    border: "1px solid #f0f0f0",
    borderLeft: `3px solid ${iconColor.value}`,
  };
});

// 图标容器样式
const iconContainerStyle = computed(() => ({
  backgroundColor: iconBg.value,
  color: iconColor.value,
  boxShadow: `0 2px 6px rgba(${hexToRgb(iconColor.value)}, 0.18)`,
  background: `linear-gradient(135deg, ${iconBg.value} 0%, #ffffff 150%)`,
}));

// 图标覆盖层样式
const iconOverlayStyle = computed(() => ({
  background: `linear-gradient(135deg, ${iconColor.value} 0%, transparent 80%)`,
}));

// 数字样式
const numberStyle = computed(() => ({
  backgroundColor: iconColor.value,
  color: "#fff",
  fontSize: "0.7rem",
  fontWeight: "bold",
}));

const handleClickAction = () => {
  agentResultModalVisible.value = true;
};

const handleCloseAgentResultModal = () => {
  agentResultModalVisible.value = false;
};
</script>

<style scoped>
.agent-card {
  position: relative;
  margin-bottom: 1rem;
}

.agent-card:not(.grouped) {
  transition: all 0.3s ease;
}

.agent-card:not(.grouped):hover {
  background-color: #fafafa;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.agent-card-animation {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fadeIn {
  animation: fadeIn 0.3s ease-in-out;
}
</style>
